//
//  NvMusicSelectionViewController.m
//  NvSellerShow
//
//  Created by dx on 17/2/7.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvMusicSelectionViewController.h"
#import "NMRangeSlider.h"
#import "MusicInfo.h"
#import "UIColor+Hex.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "Utils.h"

@interface NvMusicSelectionViewController ()<AVAudioPlayerDelegate> {
    NSArray *itemsFromGenericQuery;
    NSMutableArray *localMusicArray;
    NSMutableArray *musicLibaryArray;
}
@property (nonatomic, retain) AVAudioPlayer *player;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (nonatomic, retain) NSTimer *timer;
@property (weak, nonatomic) IBOutlet NMRangeSlider *musicSlider;
@property (weak, nonatomic) IBOutlet UIView *musicLineView;
@property (weak, nonatomic) IBOutlet UIButton *localMusicButton;
@property (weak, nonatomic) IBOutlet UIButton *musicLibaryButton;

@property (nonatomic, strong) NSMutableArray *downloadMusicArray;
@property (nonatomic, assign) BOOL play;
@end

@implementation NvMusicSelectionViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _playBtn.layer.shadowColor = [UIColor blackColor].CGColor;//阴影颜色
    _playBtn.layer.shadowOffset = CGSizeMake(0, 0);//偏移距离
    _playBtn.layer.shadowOpacity = 1;//不透明度
    _playBtn.layer.shadowRadius = 2.0;//半径
    [self configureSlider];
    [self initLocalMusicView];
    if(_songTitle.length > 0)
    {
        [self initMusicInfo];
    }
    self.title = @"音乐选择";
    [self initNavigationBarView];
}

- (void)initNavigationBarView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [backBtn setBackgroundImage:[UIImage imageFromBundle:@"back_icon"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) configureSlider {

    _musicSlider.trackImage = [UIImage imageFromBundle:@"switch_need"];
    
}

- (void)initMusicInfo {
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:_songURL] error:nil];
    //     设置循环次数，-1为一直循环
    _player.numberOfLoops = 0;
    //     准备播放
    [_player prepareToPlay];
    //     设置播放音量
    _player.volume = 10;
    //     当前播放位置，即从currentTime处开始播放，相关于android里面的seekTo方法
    _player.currentTime = _startTime.doubleValue;
    //     设置代理
    _player.delegate = self;
    _musicTitleLabel.text = _songTitle;
    _curLabel.text = [self stringWithTime:_player.currentTime];
    _durationLabel.text = [self stringWithTime:_player.duration];
    _musicSlider.lowerValue = 0;
    _musicSlider.upperValue = 1;
     CGFloat time = self.musicSlider.lowerValue * _player.duration;
    _player.currentTime = time;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key = [self.keys objectAtIndex:section];
    NSArray * array = [self.localMusicDic objectForKey:key];
    return [array count];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *v_headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    UILabel *v_headerLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, self.view.frame.size.width-30, 30)];//创建一个UILable（v_headerLab）用来显示标题
    v_headerLab.text = self.keys[section];
    v_headerLab.backgroundColor = [UIColor colorWithHexString:@"#f5f5f5"];;//设置v_headerLab的背景颜色
    v_headerLab.textColor = [UIColor colorWithHexString:@"#666666"];//设置v_headerLab的字体颜色
    v_headerLab.font = [UIFont fontWithName:@"Arial" size:19];//设置v_headerLab的字体样式和大小
    [v_headerView addSubview:v_headerLab];
    [v_headerView setBackgroundColor:[UIColor colorWithHexString:@"#f5f5f5"]];
    return v_headerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *key = [self.keys objectAtIndex:indexPath.section];
    MusicInfo *music = [[self.localMusicDic objectForKey:key] objectAtIndex:indexPath.row];
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:music.musicUrl error:nil];
    //     设置循环次数，-1为一直循环
    _player.numberOfLoops = 0;
    //     准备播放
    [_player prepareToPlay];
    //     设置播放音量
    _player.volume = 10;
    //     当前播放位置，即从currentTime处开始播放，相关于android里面的seekTo方法
    _player.currentTime = 0;
    //     设置代理
    _player.delegate = self;
    //int dur = _player.duration;
    _musicTitleLabel.text = music.musicTitle;
    _curLabel.text = [self stringWithTime:_player.currentTime];
    _durationLabel.text = [self stringWithTime:_player.duration];
    _musicSlider.lowerValue = 0;
    _musicSlider.upperValue = 1;
    double time = self.musicSlider.lowerValue * _player.duration;
    _player.currentTime = time;
    _startTime = [NSNumber numberWithDouble:time];
    time = self.musicSlider.upperValue * _player.duration;
    _endTime = [NSNumber numberWithDouble:time];;
    _songTitle = music.musicTitle;
    if([music.musicUrl isKindOfClass:[NSURL class]])
        _songURL = music.musicUrl.absoluteString;
    else
        _songURL = music.musicUrl.absoluteString;
//    [self stop];
//    _play = NO;
    [self playMusic];
    _play = YES;
}

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.keys;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuseIdentifier = @"contactCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (nil == cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    
    NSString *key = [self.keys objectAtIndex:indexPath.section];
    MusicInfo* music = [[self.localMusicDic objectForKey:key] objectAtIndex:indexPath.row];
    

    cell.textLabel.text = music.musicTitle;
    [cell setBackgroundColor:[UIColor colorWithHexString:@"#ffffff"]];
    [cell.textLabel setFont:[UIFont fontWithName:@"Arial" size:14]];
    cell.textLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    /**
     *  单元格的选中类型一定不能设置为 UITableViewCellSelectionStyleNone，如果加上这一句，全选勾选不出来
     */
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;//选中无风格
    
    //清楚UITableView底部多余的分割线
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor colorWithHexString:@"45515f"];
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor colorWithHexString:@"#999999"];
    [tableView setTableFooterView:view];
    return cell;
}

//头部高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}


-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewCellEditingStyleDelete;
    
}



#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.keys count];
}



-(void)initLocalMusicView {
    self.localMusicTableView.delegate = self;
    self.localMusicTableView.dataSource = self;
    self.localMusicTableView.tag = 1;
    [self.localMusicTableView setSectionIndexColor:[UIColor colorWithHexString:@"9ea9b6"]];
    [self.localMusicTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    self.localMusicTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    
    MPMediaQuery *everything = [MPMediaQuery songsQuery];
    itemsFromGenericQuery = [everything items];
    
    localMusicArray = [NSMutableArray array];
    musicLibaryArray = [NSMutableArray array];
    for (MPMediaItem *item in itemsFromGenericQuery) {
        MusicInfo *music = [MusicInfo musicWithItem:item];
        [musicLibaryArray addObject:music];
    }
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *files = [fileManager contentsOfDirectoryAtPath:[path stringByAppendingPathComponent:@"music"] error:nil];
    for (NSString *name in files) {
        NSBundle *musicBundle = [NSBundle bundleWithPath:[path stringByAppendingPathComponent:@"music"]];
        NSURL *url = [musicBundle URLForResource:[[name componentsSeparatedByString:@"."] firstObject] withExtension:[[name componentsSeparatedByString:@"."] lastObject]];
        MusicInfo *music = [MusicInfo new];
        music.musicTitle = [[name componentsSeparatedByString:@"."] firstObject];
        
        music.musicUrl = url;
        [localMusicArray addObject:music];
    }
    MusicManager *musicManager = [[MusicManager alloc] initWithArray:localMusicArray];
    self.localMusicDic = [musicManager divideIntoGroup];
    self.keys = [NSMutableArray arrayWithArray:[[self.localMusicDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];
}

- (IBAction)localMusicClick:(UIButton *)sender {
    self.musicLineView.centerX_LL = self.localMusicButton.centerX_LL;
    MusicManager *musicManager = [[MusicManager alloc] initWithArray:localMusicArray];
    self.localMusicDic = [musicManager divideIntoGroup];
    self.keys = [NSMutableArray arrayWithArray:[[self.localMusicDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    [self.localMusicTableView reloadData];
}

- (IBAction)musicLibaryClick:(UIButton *)sender {
    if(![self checkMediaLibraryPermissions]) {
        [Utils showMessageAlertWithTitle:@"请打开媒体资料库权限" message:@"设置-隐私-媒体资料库"];
        return;
    }
    
    self.musicLineView.centerX_LL = self.musicLibaryButton.centerX_LL;
    MusicManager *musicManager = [[MusicManager alloc] initWithArray:musicLibaryArray];
    self.localMusicDic = [musicManager divideIntoGroup];
    self.keys = [NSMutableArray arrayWithArray:[[self.localMusicDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    [self.localMusicTableView reloadData];
}

-(UIImage *)createImageWithColor:(UIColor *)color
{
    //设置长宽
    CGRect rect = CGRectMake(-1, 2, 1, 2);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resultImage;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - 检查媒体库资源
-(BOOL)checkMediaLibraryPermissions {
    __block BOOL result = NO;
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSString *version = [UIDevice currentDevice].systemVersion;
    NSLog(@"=====%f",version.doubleValue);
    if (version.doubleValue >= 9.3) {
        [MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus status){
            switch (status) {
                case MPMediaLibraryAuthorizationStatusNotDetermined: {
                    // not determined
                    NSLog(@"MediaLibrary not determined");
                    break;
                }
                case MPMediaLibraryAuthorizationStatusRestricted: {
                    // restricted
                    NSLog(@"MediaLibrary restricted");
                    break;
                }
                case MPMediaLibraryAuthorizationStatusDenied: {
                    // denied
                    NSLog(@"MediaLibrary denied");
                    break;
                }
                case MPMediaLibraryAuthorizationStatusAuthorized: {
                    // authorized
                    NSLog(@"MediaLibrary authorized");
                    result = YES;
                    break;
                }
                default: {
                    break;
                }
            }
            dispatch_semaphore_signal(sema);
        }];
    } else {
        MPMediaQuery *everything = [MPMediaQuery songsQuery];
        NSArray *items = [everything items];
        if (items == nil) {
            result = NO;
        } else {
            result = YES;
        }
        dispatch_semaphore_signal(sema);
    }
    
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    return result;
}

// 停止
- (void)stop {
    _player.currentTime = 0;
    [_player stop];
    [self removeCurrentTimer];
    [_playBtn setImage:[UIImage imageFromBundle:@"switch_play"] forState:UIControlStateNormal];
}

// 暂停
- (void)pause {
    [_player pause];
    NSLog(@"pause");
    [self removeCurrentTimer];
     [_playBtn setImage:[UIImage imageFromBundle:@"switch_play"] forState:UIControlStateNormal];
}

// 开始播放
- (void)playMusic {
    NSLog(@"start play");
    int time = self.musicSlider.lowerValue * _player.duration;
    _player.currentTime = time;
    [_player play];
    [self addCurrentTimer];
    [_playBtn setImage:[UIImage imageFromBundle:@"switch_stop"] forState:UIControlStateNormal];
}

- (void)backBtnPressed:(id)sender {
    [self stop];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)playBtnPressed:(id)sender {
    if(!_player)
        return;
    if (_play) {
        [self pause];
        _play = NO;
    }else{
        [self playMusic];
        _play = YES;
    }
}

#pragma mark ----进度条定时器处理
/**
 *  添加定时器
 */
- (void)addCurrentTimer
{
    if (![self.player isPlaying]) return;
    
    //在新增定时器之前，先移除之前的定时器
    [self removeCurrentTimer];
    
    [self updateCurrentTimer];
 
    self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateCurrentTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/**
 *  移除定时器
 */
- (void)removeCurrentTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

/**
 *  触发定时器
 */
- (void)updateCurrentTimer
{
    _curLabel.text = [self stringWithTime:_player.currentTime];
    double temp = self.player.currentTime / self.player.duration;
    if(_musicSlider.upperValue <= temp)
    {
        [self stop];
        _play = NO;
    }
    //self.musicSlider.lowerValue = temp ;
}

/**
 *  将时间转化为合适的字符串
 *
 */
- (NSString *)stringWithTime:(NSTimeInterval)time
{
    int minute = time / 60;
    int second = (int)time % 60;
    return [NSString stringWithFormat:@"%02d:%02d",minute, second];
}

- (IBAction)musicSliderValueChanged:(id)sender {
    double time = self.musicSlider.lowerValue * _player.duration;
    self.curLabel.text = [self stringWithTime:time];
    _player.currentTime = time;
    _startTime = [NSNumber numberWithDouble:time];
    time = self.musicSlider.upperValue * _player.duration;
    self.durationLabel.text = [self stringWithTime:time];
    _endTime = [NSNumber numberWithDouble:time];
}

- (IBAction)selectBtnPressed:(id)sender {
    if(_player == nil)
        return;
    [self stop];
    if ([_songURL containsString:@"ipod-library://"]) {
        [Utils showConfirmAlertWithTitle:@"版权提示" message:@"资源库音乐可能有版权问题确定使用吗?" yesTitle:@"确定" yesAction:^{
            if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishSelectMusic:MusicUrl:StartTime:EndTime:)] ==YES) {
                [self.delegate didFinishSelectMusic:_songTitle MusicUrl:_songURL StartTime:_startTime EndTime:_endTime];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }];
    } else {
        if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishSelectMusic:MusicUrl:StartTime:EndTime:)] ==YES) {
            [self.delegate didFinishSelectMusic:_songTitle MusicUrl:_songURL StartTime:_startTime EndTime:_endTime];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }

}

@end
